import { baseRoutes } from '@/router/routes.js'
const routes = baseRoutes[0]
const MENU_PERMISSION_MAP = {}
// 根据一级路由和二级路由生成侧边栏菜单并且生产对应的权限列表
export const menuConfig = [...routes.children.map((item => {
    if (item.meta.isHideOnMenu) {
        return null
    }
    const itemPath = baseRoutes[0].path + item.path
    MENU_PERMISSION_MAP[itemPath] = item.meta.permission || []
    const itemChildren = item.children.map(child => {
        const childrenPath = itemPath + '/' + child.path
        if (child.meta.isHideOnMenu) {
            return null
        }
        MENU_PERMISSION_MAP[childrenPath] = child.meta.permission || []
        return {
            title: child.meta.title,
            path: itemPath + '/' + child.path,
        }
    }).filter(Boolean) // 移除空值
    return {
        path: itemPath,
        title: item.meta.title,
        icon: item.meta.icon,
        children: itemChildren.length > 0 ? itemChildren : null
    }
})).filter(Boolean) // 移除空值
]



// 检查用户是否有访问菜单项的权限
export function hasMenuPermission(menuPath, userPermissions) {
    const requiredPermissions = MENU_PERMISSION_MAP[menuPath]
    if (!requiredPermissions) return true // 如果没有配置权限要求，默认允许访问

    // 只要用户拥有该菜单所需的任一权限即可访问
    return requiredPermissions.some(permission => userPermissions.includes(permission))
}

// 过滤菜单配置，仅保留用户有权限访问的菜单项
export function filterMenuByPermissions(menuConfig, userPermissions) {
    return menuConfig
        .filter(menu => hasMenuPermission(menu.path, userPermissions))
        .map(menu => {
            if (menu.children) {
                const filteredChildren = menu.children.filter(
                    child => hasMenuPermission(child.path, userPermissions)
                )

                // 如果过滤后没有子菜单，则不显示该父菜单
                if (filteredChildren.length === 0) {
                    return null
                }

                return {
                    ...menu,
                    children: filteredChildren
                }
            }
            return menu
        })
        .filter(Boolean) // 移除空值
}

// 生成用户可访问的路由表
export function generateAccessibleRoutes(menuConfig, userPermissions) {
    const routes = []

    function traverseMenu(menu) {
        if (hasMenuPermission(menu.path, userPermissions)) {
            routes.push(menu.path)
        }

        if (menu.children) {
            menu.children.forEach(traverseMenu)
        }
    }

    menuConfig.forEach(traverseMenu)
    return routes
}